layui.extend({
        conf: 'config',
        api: 'lay/modules/api',
        view: 'lay/modules/view'
    })
    .define(['conf', 'view', 'api', 'jquery', 'table','form','laydate','tree'], function (exports) {
        var conf = layui.conf;
        var view = layui.view;
        var table = layui.table;
        var element = layui.element;
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var form = layui.form;
        var $body = $('body');
        var self = {};
        var loadBar = layui.loadBar;
        var windowWidth = $(window).width();
        self.route = layui.router();
        self.api = layui.api;
        self.closeOnceHashChange = false;
        self.ie8 = view.ie8;
        self.get = view.request;
        self.appBody = null;
        self.shrinkCls = 'nepadmin-sidebar-shrink';
        self.isInit = false;
        self.routeLeaveFunc = null;
        self.loginToken = null;
        self.routeLeave = function (callback) {
            this.routeLeaveFunc = callback
        };
        //获取数据字典储存并缓存
        self.getDict = function () {
            self.get({
                api: 'getDict',
                success:function (res) {
                    if(res.data){
                        var dictList = {};
                        res.data.forEach(function (obj,index) {
                            dictList[obj.dictCode] = obj.valList;
                        });
                        //缓存数据字典
                        self.data(
                            {
                                key: 'dictList',
                                value: dictList
                            }
                        );
                    }
                }
            })
        };
        //获取路由中加密参数
        self.routeParams = function () {
            var list = self.route.search[conf.encryptionlogo]
            if(params) {
                var params = self.decrypt(params);
                var arr = params.split('&');
                var res = {};
                for (var i = 0; i < arr.length; i++) {
                    res[arr[i].split('=')[0]] = arr[i].split('=')[1];
                }
                return res;
            }
        };
        //href 跳转页面  加密参数
        self.href = function (url,params) {
            location.hash = url+'/'+conf.encryptionlogo+'='+self.encrypt(self.jsonToUrlParams(params));
        };
        //json 对象转 URL 参数
        self.jsonToUrlParams = function (json) {
            var params = Object.keys(json).map(function (key) {
                return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
            }).join("&");
            return params;
        };
        //加密
        self.encrypt = function (str) {
            var pwd = conf.pwdCode;
            var prand = "";
            for(var i=0; i<pwd.length; i++) {
                prand += pwd.charCodeAt(i).toString();
            }
            var sPos = Math.floor(prand.length / 5);
            var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
            var incr = Math.ceil(pwd.length / 2);
            var modu = Math.pow(2, 31) - 1;
            if(mult < 2) {
                console.log("算法找不到合适的哈希。请选择一个不同的密码。可能的考虑是选择更复杂或更长的密码。");
                return null;
            }
            var salt = Math.round(Math.random() * 1000000000) % 100000000;
            prand += salt;
            while(prand.length > 10) {
                prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
            }
            prand = (mult * prand + incr) % modu;
            var enc_chr = "";
            var enc_str = "";
            for(var i=0; i<str.length; i++) {
                enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
                if(enc_chr < 16) {
                    enc_str += "0" + enc_chr.toString(16);
                } else enc_str += enc_chr.toString(16);
                prand = (mult * prand + incr) % modu;
            }
            salt = salt.toString(16);
            while(salt.length < 8)salt = "0" + salt;
            enc_str += salt;
            return enc_str;
        };
        //解密
        self.decrypt = function (str) {
            var pwd = conf.pwdCode;
            var prand = "";
            for(var i=0; i<pwd.length; i++) {
                prand += pwd.charCodeAt(i).toString();
            }
            var sPos = Math.floor(prand.length / 5);
            var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
            var incr = Math.round(pwd.length / 2);
            var modu = Math.pow(2, 31) - 1;
            var salt = parseInt(str.substring(str.length - 8, str.length), 16);
            str = str.substring(0, str.length - 8);
            prand += salt;
            while(prand.length > 10) {
                prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
            }
            prand = (mult * prand + incr) % modu;
            var enc_chr = "";
            var enc_str = "";
            for(var i=0; i<str.length; i+=2) {
                enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
                enc_str += String.fromCharCode(enc_chr);
                prand = (mult * prand + incr) % modu;
            }
            return enc_str;
        };

        //下拉框
        self.select = function (elem,dictType,defaultVal) {
            var dictTypeVals = self.data()['dictList'][dictType];
            if(dictTypeVals){
                var options = ['<option value="">请选择</option>'];
                dictTypeVals.forEach(function (obj,index) {
                    if(defaultVal && defaultVal == obj.id){
                        options.push('<option value="'+obj.id+'" selected>'+obj.valName+'</option>')
                    }else{
                        options.push('<option value="'+obj.id+'">'+obj.valName+'</option>')
                    }
                });
                $(elem).html(options);
                layui.form.render();
            }
        };
        self.render = function (elem) {
            if (typeof elem == 'string') elem = $('#' + elem);
            var action = elem.get(0).tagName == 'SCRIPT' ? 'next' : 'find';
            elem[action]('[is-template]').remove();
            view.parse(elem)
        };
        self.getLoginToken = function () {
            if (self.loginToken == null) {
                self.loginToken =
                    self.data()[conf.tokenName] ||
                    layui.sessionData(conf.tableName, conf.tokenName)
            }
            return self.loginToken
        };
        //实例化表格
        self.table = function (params) {
            var done = params.done;
            if (params.url) {
                if(params.url.indexOf("json")!=0){
                    params.url = conf.requestUrl + params.url
                }
            }else if (params.api) {
                if (!layui.api[params.api]) {
                    self.log('请求错误 api.' + params.api + ' 不存在');
                    return
                }
                params.url = conf.requestUrl + layui.api[params.api] + ((params.urlStr)?params.urlStr:"")
            }
            params = $.extend({
                formFilter: '',  //搜索表单过滤
                tableFilter: '',        //表格过滤
                height: 'full-240',     //表格高度
                page: true,
                loading: conf.table.loading,  //是否显示加载条
                headers: conf.requestHeaders || {},
                skin: 'line',
                request: conf.table.request,
                parseData: function(res){   //res 即为原始返回的数据
                    //如果是直接赋值的方式，curr当前页码、 data为当前页数据、count为数据总长度
                    var status = res[conf.response.statusName];
                    if (status != conf.response.statusCode.ok) {
                        loadBar.error()
                        if (status == conf.response.statusCode.logout) {
                            if(res[conf.response.msgName]){
                                layer.alert(res[conf.response.msgName], {icon: 7, title: "提示"},function () {
                                    layui.admin.logout()
                                });
                            }else{
                                layer.alert('认证失败,需要重新登录', {icon: 7, title: "提示"},function () {
                                    layui.admin.logout()
                                });
                            }
                        } else if (status == conf.response.statusCode.error) {
                            if(res[conf.response.msgName]){
                                layer.msg(res[conf.response.msgName], {anim: 6,icon: 5, time: 1500});
                            }else{
                                layer.msg("未知错误", {anim: 6,icon: 5, time: 1500});
                            }
                        } else if (status == conf.response.statusCode.lack) {
                            if(res[conf.response.msgName]){
                                layer.msg(res[conf.response.msgName], {anim: 6,icon: 4, time: 1500});
                            }else{
                                layer.msg("无权限", {anim: 6,icon: 4, time: 1500});
                            }
                        }else {
                            self.log(
                                '返回状态码异常：' +
                                res[conf.response.statusName] +
                                '\n请求URL：' +
                                params.url
                            )
                        }
                    }else{//处理后端返回数据结构
                        loadBar.finish()
                        if(params.page == false){ //不分页的数据结构
                            return {
                                "code": res.code, //解析接口状态
                                "msg": res.msg, //解析提示文本
                                "data": res.data //解析数据列表
                            };
                        }else{ //分页的数据结构
                            return {
                                "code": res.code, //解析接口状态
                                "msg": res.msg, //解析提示文本
                                "count": res.data.totalCount, //解析数据长度
                                "data": res.data.list //解析数据列表
                            };
                        }
                    }
                },
                done: function(res, curr, count){
                    //验证权限
                    view.permsVerify();
                    if ($.isFunction(done)) done(res, curr, count)
                }
            },params);
            //设置表格自动提交搜索条件
            if(params.formFilter){
                var formJson = form.val(params.formFilter);
                params.where = formJson;
            }
            //设置token
            if (conf.tokenName) {
                var token = layui.admin.getLoginToken();
                if (token) params.headers[conf.tokenName] = token
            }
            if(params.loading) {
                loadBar.start();
            }
            //加载表格
            table.render(params);
            //初始化事件
            self.initEvent(params);
        };
        //layui 表格 初始化事件
        self.initEvent = function (options) {
            if(!options.tableFilter){
                console.log("tableFilter属性不能空")
            }else{
                /**
                 * ***** 自定义 事件监听 ******
                 */
                if (options.tools && options.tools != {} && options.tableFilter) {
                    //监听行工具事件
                    table.on('tool(' + options.tableFilter + ')', function (obj) {
                        var data = obj.data;
                        if ($.isFunction(options.tools[obj.event])) {
                            options.tools[obj.event](data, this);
                        }
                    });
                    //监听头工具栏事件
                    table.on('toolbar(' + options.tableFilter + ')', function (obj) {
                        var data = obj.data;
                        if ($.isFunction(options.tools[obj.event])) {
                            options.tools[obj.event](data, this);
                        }
                    });
                    if (options.rowClick) {    //默认关闭行点击事件
                        //监听行单击事件（单击事件为：rowClick）
                        table.on('row(' + options.tableFilter + ')', function (obj) {
                            var data = obj.data;
                            if ($.isFunction(options.tools['rowClick'])) {
                                options.tools['rowClick'](data, obj, this);
                            }
                            //标注选中样式
                            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                        });
                        //双击事件  函数  rowDbClick （双击事件为：rowDbClick）
                        table.on('rowDouble(' + options.tableFilter + ')', function (obj) {
                            var data = obj.data;
                            if ($.isFunction(options.tools['rowDbClick'])) {
                                options.tools['rowDbClick'](data, obj, this);
                            }
                            //标注选中样式
                            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                        });
                    }
                }
                /**
                 * ***监听 from 、table 两种类型     必须填写 **** 格式******
                 *
                 *filter:[{
                            types:'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools 请使用 tools 属性
                            filterTypes: 'switch',   //
                            filterName: 'enabledDemo',
                            returnData : function (obj) {
                                layer.alert('编辑行：<br>'+ JSON.stringify(obj));
                            }
                        }
                 ],    //表单监听
                 */
                if (options.filter != undefined && options.filter != null) {
                    for (var i = 0; i < options.filter.length; i++) {
                        if (options.filter[i].types == 'form') {
                            form.on(options.filter[i].filterTypes + '(' + options.filter[i].filterName + ')', options.filter[i].returnData);
                        } else {
                            table.on(options.filter[i].filterTypes + '(' + options.tableFilter + ')', options.filter[i].returnData);
                        }
                    }
                }
            }
        };
        /**
         *  layui 提交表单搜素
         * @param formFilter  表单过滤器
         * @param tableElem  指定原始 table 容器的选择器或 DOM，方法渲染方式必填
         * @param homePage   首页  boolean
         */
        self.tableSearch = function (formFilter,tableElem,homePage) {
            if(homePage && homePage == true){
                table.reload(tableElem,{
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where:form.val(formFilter)
                });
            }else{
                table.reload(tableElem,{
                    where:form.val(formFilter)
                });
            }
        };

        //跳转登录页
        self.logout = function () {
            localStorage.removeItem('permissions')
            self.data({key: conf.tokenName, remove: true})
            self.data({key: conf.tokenName, remove: true}, sessionStorage)
            self.loginToken = null
            self.navigate(conf.loginPage)
        };
        self.login = function (token, data, isSession) {
            self.data(
                {
                    key: conf.tokenName,
                    value: token
                },
                isSession && sessionStorage
            )

            if ($.isPlainObject(data)) {
                var disableData = []
                layui.each(data, function (key) {
                    disableData.push({
                        key: key,
                        value: data[key]
                    })
                })
                self.data(disableData)
            }
        };
        //初始化整个页面
        self.initPage = function (initCallback) {
            //加载样式文件
            layui.each(layui.conf.style, function (index, url) {
                layui.link(url + '?v=' + conf.v)
            })

            self.initView(self.route)
        };
        /**
         * 金额验证
         * @param elem  指定原始 table 容器的选择器或 DOM，方法渲染方式必填
         */
        self.moneyValid = function(elem){
            $(elem).on('input propertychange',function(){
                //如果输入非数字，则替换为''
                this.value = this.value.replace(/[^\d\.]/g, '');
                //必须保证第一个为数字而不是.
                this.value = this.value.replace(/^\./g,'');
                //保证只有出现一个.而没有多个.
                this.value = this.value.replace(/\.{2,}/g,'.');
                //保证.只出现一次，而不能出现两次以上
                this.value = this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                //只能输入两位小数
                this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
            });
        };
        //post 请求
        self.post = function (params) {
            view.request($.extend({type: 'post'}, params))
        };
        /**
         * 递归处理数据
         * @param dataList   数组数据
         * @param id    标识ID
         * @param pid   上级ID
         */
        self.recursive = function (dataList,idName,pidName) {
            //获取子集
            function getChild(id,dataList) {
                var children = [];
                dataList.forEach(function (obj,index) {
                    delete obj.icon;
                    delete obj.url;
                    if(obj[pidName] == id){
                        children.push(obj);
                    }
                });
                if(children.length == 0){
                    return null;
                }else{
                    children.forEach(function (childrenObj,number) {
                        childrenObj.childList = getChild(childrenObj[idName],dataList)
                    });
                }
                return children;
            }
            return  getChild(0,dataList);
        };
        //初始化视图区域
        self.initView = function (route) {
            if (!self.route.href || self.route.href == '/') {
                self.route = layui.router('#' + conf.entry)
                route = self.route
            }
            route.fileurl = '/' + route.path.join('/')
            //判断登录页面
            if (conf.loginCheck == true) {
                if (self.getLoginToken()) {
                    if (route.fileurl == conf.loginPage) {
                        self.navigate('/')
                        return
                    }
                } else {
                    if (route.fileurl != conf.loginPage) {
                        self.logout()
                        return
                    }
                }
            }

            if ($.inArray(route.fileurl, conf.indPage) === -1) {
                var loadRenderPage = function (params) {
                    if (conf.viewTabs == true) {
                        view.renderTabs(route)
                    } else {
                        view.render(route.fileurl)
                    }
                }

                if (view.containerBody == null) {
                    //加载layout文件
                    view.renderLayout(function () {
                        //重新渲染导航
                        element.render('nav', 'nepadmin-sidebar')
                        //加载视图文件
                        loadRenderPage()
                    })
                } else {
                    //layout文件已加载，加载视图文件
                    loadRenderPage()
                }
            } else {
                //加载单页面
                view.renderIndPage(route.fileurl, function () {
                    if (conf.viewTabs == true) view.tab.clear()
                })
            }
        }
        //根据当前加载的URL高亮左侧导航
        self.sidebarFocus = function (url) {
            url = url || self.route.href
            var elem = $('#app-sidebar')
                .find('[lay-href="' + url + '"]')
                .eq(0)
            if (elem.length > 0) {
                elem.parents('.layui-nav-item').addClass('layui-nav-itemed')
                elem.click()
            }
        }
        self.flexible = function (open) {
            if (open == true) {
                view.container.removeClass(self.shrinkCls)
            } else {
                view.container.addClass(self.shrinkCls)
            }
        }
        self.on = function (name, callback) {
            return layui.onevent(conf.eventName, 'system(' + name + ')', callback)
        }
        self.event = function (name, params) {
            layui.event(conf.eventName, 'system(' + name + ')', params)
        }
        //加载样式文件
        self.csshref = function (name) {
            name = name == undefined ? self.route.path.join('/') : name
            return conf.css + 'views/' + name + '.css' + '?v=' + conf.v
        }
        self.prev = function (n) {
            if (n == undefined) n = -1
            window.history.go(n)
        }
        //跳转页面
        self.navigate = function (url) {
            if (url == conf.entry) url = '/'
            window.location.hash = url
        };
        //设置菜单显示数值
        self.setMenuNum = function (menuId,num) {
            var menuHtml = $("#menu_"+menuId).html();
            $("#menu_"+menuId).html(menuHtml + '<span class="layui-badge">'+num+'</span>')
        };
        //清空菜单显示数值
        self.removeMenuNum = function (menuId) {
            $("#menu_"+menuId).find(".layui-badge").remove();
        };
        /**
         * 缓存
         *  存  self.data({key: 'dictList',value: dictList});
         *  取  self.data()['dictList']
         * @param settings
         * @param storage
         */
        self.data = function (settings, storage) {
            if (settings == undefined) return layui.data(conf.tableName)
            if ($.isArray(settings)) {
                layui.each(settings, function (i) {
                    layui.data(conf.tableName, settings[i], storage)
                })
            } else {
                layui.data(conf.tableName, settings, storage)
            }
        }
        //连接 socket
        self.socketConn = function () {
            var websocket = null;
            if('WebSocket' in window){
                websocket = new WebSocket(conf.webSocketUrl+self.getLoginToken());
            }else{
                self.error("您的浏览器不支持websocket");
            }
            websocket.onerror = function(){
                setMessageInHtml("send error！");
            }
            websocket.onopen = function(){
                setMessageInHtml("connection success！welcome")
            }
            websocket.onmessage  = function(event){
                console.log(event)
                var parse = JSON.parse(event.data);
                if(parse.data!=""){
                    setMessageInHtml(parse.data.split("--")[0]);
                    setMessageInHtmlCount(parse.message);
                }else{
                    setMessageInHtmlCount(parse.message);

                }

            }
            websocket.onclose = function(){
                setMessageInHtml("closed websocket!")
            }
            window.onbeforeunload = function(){
                clos();
            }
            function setMessageInHtml(message){
                console.log(message)
            }
            function setMessageInHtmlCount(message){
                console.log(message)
            }
            function clos(){
                websocket.close(3000,"强制关闭");
            }
            function send(){
                var msg = document.getElementById('text').value;
                websocket.send(msg);
            }
        };
        /*提示框*/
        self.confirm = function (title, success) {
            layer.confirm(title, {icon: 3, title: '提示信息'}, function (index) {
                layer.close(index);
                if ($.isFunction(success)) success()
            });
        }
        /*成功提示*/
        self.success = function (title, success) {
            layer.msg(title, {anim: 6,icon: 6, time: 1500}, success);
        }
        /*警告提示*/
        self.warn = function (title, success) {
            layer.msg(title, {anim: 6,icon: 7, time: 1500}, success);
        }
        /*警告提示*/
        self.warnAlert = function (title, success) {
            layer.alert(title, {icon: 7, title: "提示"}, success);
        }
        /*错误提示*/
        self.error = function (title, success) {
            layer.msg(title, {anim: 6,icon: 5, time: 1500}, success);
        }
        self.isUrl = function (str) {
            return /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/.test(
                str
            )
        }
        //打开一个页面  弹框
        self.popup = function (params) {
            var url = params.url || ''
            var success = params.success || function () {}
            params.skin = 'layui-layer-admin-page'
            var defaultParams = {
                type: 1,
                area: ['90%', '90%'], //宽高
                shadeClose: true
            }
            if (self.isUrl(url)) {
                params.type = 2
                params.content = url
                layer.open($.extend(defaultParams, params))
                return
            }
            view.tab.del(url)
            if(params.type == 3){  //不弹框  ,页面     路由地址不更新
                view.render(conf.views + url,params.success,params.data)
            }else {
                view.loadHtml(conf.views + url, function (res) {
                    var htmlElem = $('<div>' + res.html + '</div>')

                    if (params.title === undefined) {
                        params.title = htmlElem.find('title').text() || '信息'
                        if (params.title) htmlElem.find('title').remove()
                    }

                    params.content = htmlElem.html()
                    params.success = function (layer, index) {
                        if(params.data){
                            layer.params = params.data;
                        }
                        //加载模板
                        view.parse(layer)
                        //回调
                        success(layer, index)
                        //重新对面包屑进行渲染
                        element.render('breadcrumb', 'nepadmin-breadcrumb')
                    }
                    params = $.extend(defaultParams, params)
                    layer.open($.extend(defaultParams, params))
                })
            }
        }

        //当小于这个尺寸的时候会进行手机端的适配
        var mobileWidth = 991
        var isMobileAdapter = false

        function mobileAdapter() {
            self.flexible(false)
            var device = layui.device()
            if (device.weixin || device.android || device.ios) {
                //点击空白处关闭侧边栏
                $(document).on('click', '#' + conf.containerBody, function () {
                    if (
                        windowWidth < mobileWidth && !view.container.hasClass(self.shrinkCls)
                    ) {
                        self.flexible(false)
                    }
                })
            }
            isMobileAdapter = true
        }

        $(window).on('resize', function (e) {
            if (windowWidth < mobileWidth) {
                if (isMobileAdapter == true) return
                mobileAdapter()
            } else {
                isMobileAdapter = false
            }
        })

        $(window).on('hashchange', function (e) {
            //移动端跳转链接先把导航关闭
            if (windowWidth < mobileWidth) {
                self.flexible(false)
            }
            self.route = layui.router()
            layer.closeAll()
            self.initView(self.route)
        })

        //回车提交 form 表单
        $(document).on('keydown', function (e) {
            var ev = document.all ? window.event : e
            if (ev.keyCode == 13) {
                var form = $(':focus').parents('.layui-form')
                form.find('[lay-submit]').click()
            }
        })

        $(document).on('click', '[lay-href]', function (e) {
            var href = $(this).attr('lay-href')
            var target = $(this).attr('target')
            /* 加密 url 参数 start  */
            if(href.indexOf("=") >= 0){  //URL包含参数
                var path = href.split("/");
                var search = path[path.length-1];
                path.splice(path.length-1,1);
                //加密参数
                href = path.join("/") + "/"+conf.encryptionlogo+"="+self.encrypt(search);
            }
            /* 加密 url 参数 end  */
            if (href == '') return
            if (self.isUrl(href)) {
                next()
            }

            function next() {
                target == '__blank' ? window.open(href) : self.navigate(href)
            }
            if ($.isFunction(self.routeLeaveFunc)) {
                self.routeLeaveFunc(self.route, href, next)
            } else {
                next()
            }

            return false
        })
        $(document).on('click', '[lay-popup]', function (e) {
            var params = $(this).attr('lay-popup')
            self.popup(
                params.indexOf('{') === 0
                    ? new Function('return ' + $(this).attr('lay-popup'))()
                    : {url: params}
            )
            return false
        })
        $(document).on('mouseenter', '[lay-tips]', function (e) {
            var title = $(this).attr('lay-tips')
            var dire = $(this).attr('lay-dire') || 3
            if (title) {
                layer.tips(title, $(this), {
                    tips: [dire, '#263147']
                })
            }
        })
        $(document).on('mouseleave', '[lay-tips]', function (e) {
            layer.closeAll('tips')
        })
        //注册自定义点击事件
        $(document).on('click', '*[' + conf.eventName + ']', function (e) {
            self.event($(this).attr(conf.eventName), $(this))
        })
        var shrinkSidebarBtn =
            '.' + self.shrinkCls + ' #app-sidebar .layui-nav-item a'

        $(document).on('click', shrinkSidebarBtn, function (e) {
            if (isMobileAdapter == true) return
            var chileLength = $(this)
                .parent()
                .find('.layui-nav-child').length
            if (chileLength > 0) {
                self.flexible(true)
                layer.closeAll('tips')
            }
        })
        $(document).on('mouseenter', shrinkSidebarBtn, function (e) {
            var title = $(this).attr('title')
            if (title) {
                layer.tips(title, $(this).find('.layui-icon'), {
                    tips: [2, '#263147']
                })
            }
        })
        $(document).on('mouseleave', shrinkSidebarBtn, function (e) {
            layer.closeAll('tips')
        })

        self.on('flexible', function (init) {
            var status = view.container.hasClass(self.shrinkCls)
            self.flexible(status)
            self.data({key: 'flexible', value: status})
        })
        //刷新
        self.on('refresh', function (e) {
            var url = self.route.path.join("/");
            if (conf.viewTabs == true) {
                view.tab.refresh(url);
            } else {
                view.render(url)
            }
        })
        //修改密码
        self.on('updatePassword', function (e) {
            self.popup({
                url:'/sys/login/update_password',
                title: '修改密码',
                offset:'rt',
                area:['400px','100%'],
                anim:2,
                data: layui.admin.data()['user'],
                success:function (layer, index) {
                    var updatePassword = new UpdatePassword(self,layui.form,layer, index,$);
                    updatePassword.init();
                }
            });
        })
        //刷新当前页面
        self.refresh = function () {
            var url = self.route.href;
            if (conf.viewTabs == true) {
                view.tab.refresh(url);
            } else {
                view.render(url)
            }
        }

        self.on('prev', function (e) {
            self.prev()
        })
        //退出登录
        self.on('logout', function (e) {
            self.post({
                api:'logout',
                data:JSON.stringify({t:new Date().getTime()}),
                success:function (res) {
                    if(res.code == 0){
                        self.logout()
                    }
                }
            });
        });
        //便签
        self.on('note',function (e) {
            self.popup({
                url:'popup/note',
                title:'便签', 'offset':'rt',
                area:['400px','100%'],
                anim:2
            })
        });

        //切换全屏
        self.on('fullscreen', function (e) {
            var normalCls = 'layui-icon-screen-full'
            var activeCls = 'layui-icon-screen-restore'
            var ico = e.find('.layui-icon')

            if (ico.hasClass(normalCls)) {
                var e = document.body
                e.webkitRequestFullScreen
                    ? e.webkitRequestFullScreen()
                    : e.mozRequestFullScreen
                        ? e.mozRequestFullScreen()
                        : e.requestFullScreen && e.requestFullscreen()
                ico.removeClass(normalCls).addClass(activeCls)
            } else {
                var e = document
                e.webkitCancelFullScreen
                    ? e.webkitCancelFullScreen()
                    : e.mozCancelFullScreen
                        ? e.mozCancelFullScreen()
                        : e.cancelFullScreen
                            ? e.cancelFullScreen()
                            : e.exitFullscreen && e.exitFullscreen()
                ico.removeClass(activeCls).addClass(normalCls)
            }
        })

        if (windowWidth <= mobileWidth) {
            mobileAdapter()
        } else {
            var flexibleOpen = self.data().flexible
            self.flexible(flexibleOpen === undefined ? true : flexibleOpen)
        }

        //屏幕类型
        self.screen =function(){
            var width = windowWidth
            if(width >= 1200){
                return 3; //大屏幕
            } else if(width >= 992){
                return 2; //中屏幕
            } else if(width >= 768){
                return 1; //小屏幕
            } else {
                return 0; //超小屏幕
            }
        };

        //主题设置
        self.theme = function (options) {
            var theme = conf.theme
                , local = layui.data(conf.tableName)
                , id = 'LAY_layadmin_theme'
                , style = document.createElement('style')
                , styleText = laytpl([
                //主题色
                '.layui-side,'
                , '.layadmin-pagetabs .layui-tab-title li:after,'
                , '.layadmin-pagetabs .layui-tab-title li.layui-this:after,'
                , '.layui-layer-admin .layui-layer-title,'
                , '.layadmin-side-shrink .layui-side .layui-nav>.layui-nav-item>.layui-nav-child,'
                , '.layui-nav-itemed>.layui-nav-child'
                , '{background-color:{{d.color.main}} !important;}'

                //选中色
                , '.layui-nav-tree .layui-this,'
                , '.layui-nav-tree .layui-this>a,'
                , '.layui-nav-tree .layui-nav-child dd.layui-this,'
                , '.layui-nav-tree .layui-nav-child dd.layui-this a'
                , '{background-color:{{d.color.selected}} !important;}'

                //logo
                , '.layui-layout-admin .layui-logo{background-color:{{d.color.logo || d.color.main}} !important;}'

                //头部色
                , '{{# if(d.color.header){ }}'
                , '.layui-layout-admin .layui-header{background-color:{{ d.color.header }};}'
                , '.layui-layout-admin .layui-header a,'
                , '.layui-layout-admin .layui-header a cite{color: #f8f8f8;}'
                , '.layui-layout-admin .layui-header a:hover{color: #fff;}'
                , '.layui-layout-admin .layui-header .layui-nav .layui-nav-more{border-top-color: #fbfbfb;}'
                , '.layui-layout-admin .layui-header .layui-nav .layui-nav-mored{border-color: transparent; border-bottom-color: #fbfbfb;}'
                , '.layui-layout-admin .layui-header .layui-nav .layui-this:after, .layui-layout-admin .layui-header .layui-nav-bar{background-color: #fff; background-color: rgba(255,255,255,.5);}'
                , '.layadmin-pagetabs .layui-tab-title li:after{display: none;}'
                , '{{# } }}'
            ].join('')).render(options = $.extend({}, local.theme, options))
                , styleElem = document.getElementById(id);

            //添加主题样式
            if ('styleSheet' in style) {
                style.setAttribute('type', 'text/css');
                style.styleSheet.cssText = styleText;
            } else {
                style.innerHTML = styleText;
            }
            style.id = id;

            styleElem && $body[0].removeChild(styleElem);
            $body[0].appendChild(style);
            $body.attr('layadmin-themealias', options.color.alias);

            //本地存储记录
            local.theme = local.theme || {};
            layui.each(options, function (key, value) {
                local.theme[key] = value;
            });
            layui.data(conf.tableName, {
                key: 'theme'
                , value: local.theme
            });
        }

        //初始化主题
        self.initTheme = function (index) {
            var theme = conf.theme;
            index = index || 0;
            if (theme.color[index]) {
                theme.color[index].index = index;
                self.theme({
                    color: theme.color[index]
                });
            }
        }

        //初始
        !function () {
            //主题初始化，本地主题记录优先，其次为 initColorIndex
            var local = layui.data(conf.tableName);
            if (local.theme) {
                self.theme(local.theme);
            } else if (conf.theme) {
                self.initTheme(conf.theme.initColorIndex);
            }

            //禁止水平滚动
            $body.addClass('layui-layout-body');
            //移动端强制不开启页面标签功能
             var width = windowWidth;
             if (width >= 1200) {
                return; //大屏幕
             } else if (width >= 992) {
                return; //中屏幕
             } else if (width >= 768) {
                return; //小屏幕
             } else {
                delete conf.viewTabs; //超小屏幕
             }

            //不开启页面标签时
            if (!conf.viewTabs) {
                var container = $('#' + conf.container);
                container.addClass('layadmin-tabspage-none');
            }
            var device = layui.device();
            //低版本IE提示
            if (device.ie && device.ie < 10) {
                view.error('IE' + device.ie + '下访问可能不佳，推荐使用：Chrome / Firefox / Edge 等高级浏览器', {
                    offset: 'auto'
                    , id: 'LAY_errorIE'
                });
            }

        }();
        //事件
        //屏幕类型
        //主题设置
        self.on('setTheme', function (othis) {
            var THIS = 'layui-this';
            var index = othis.data('index')
                , nextIndex = othis.siblings('.layui-this').data('index');

            if (othis.hasClass(THIS)) return;

            othis.addClass(THIS).siblings('.layui-this').removeClass(THIS);
            self.initTheme(index);
        });

        exports('admin', self)
    });
